package cn.hfatec.shms.system.menu.action;

import cn.hfatec.JsonResponse;
import cn.hfatec.constants.SysContant;
import cn.hfatec.freemarker.FreeMarkerUtil;
import cn.hfatec.shms.base.ShmsBaseAction;
import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.constants.ShmsConstant;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.system.menu.model.Menu;
import cn.hfatec.shms.system.menu.model.MenuParams;
import cn.hfatec.shms.system.menu.service.MenuService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;


/**
 * @author hfatec codegen
 * @version 1.0
 *          <p/>
 *          the JAVA code is generate by middlegen
 */
@Controller
@RequestMapping("/system/menu")
public class MenuAction extends ShmsBaseAction {

    //服务层
    @Resource(name = "MenuService")
    private MenuService menuService;


    /**
     * 查询列表
     */
    @RequestMapping("/list")
    public String list(MenuParams menuParams, Model model) throws InvocationTargetException, IllegalAccessException {
        List<Menu> allMenuList = menuService.queryMenuTable(menuParams);
        List MenuList = menuService.getMenuList(ShmsConstant.ROOT_MENU_ID, allMenuList);
        model.addAttribute("yesOrNoTypeList", CodeInfoCache.getCodeInfo(CodeType.YES_OR_NO));
        model.addAttribute("menusTable", MenuList);
        return "/system/menu/list";
    }

    /**
     * 异步查询列表
     */
    @RequestMapping("/ajaxList")
    @ResponseBody
    public String ajaxList(MenuParams menuParams, Model model) {
        try {
            list(menuParams, model);
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/menu/table", model)).toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到新增页
     */
    @RequestMapping("/goAdd")
    @ResponseBody
    public String goAdd(String parentMenuId, Model model) {
        try {
            Menu menu = new Menu();
            menu.setParentMenuId(parentMenuId);
            model.addAttribute("menu", menu);
            model.addAttribute("yesOrNoTypeList", CodeInfoCache.getCodeInfo(CodeType.YES_OR_NO));
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/menu/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 跳转到编辑页
     */
    @RequestMapping("/goEdit")
    @ResponseBody
    public String goEdit(Integer id, Model model) {

        try {
            Menu menu = menuService.getMenu(id);
            model.addAttribute("menu", menu);
            model.addAttribute("yesOrNoTypeList", CodeInfoCache.getCodeInfo(CodeType.YES_OR_NO));
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, "", FreeMarkerUtil.render("/system/menu/form", model)).toString();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonResponse.error;
    }

    /**
     * 根据IDs删除数据
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String deleteMenu(Integer id, String menuId) {
        try {
            MenuParams menuParams = new MenuParams();
            List List = menuService.queryMenuTable(menuParams);
            List menuList = menuService.getMenuList(menuId, List);
            if (menuList.size() == 0) {
                menuService.deleteMenu(id, menuId);
            } else {
                logger.error("请先删除子菜单，再删除该菜单！");
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.DELETE_ERROR_MESSAGE).toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据" + id + "删除异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.DELETE_ERROR_MESSAGE).toString();
        }
        return new JsonResponse(JsonResponse.RETURN_SUCCESS, SysContant.DELETE_SUCCESS_MESSAGE).toString();
    }

    /**
     * 保存数据
     */
    @RequestMapping("/save")
    @ResponseBody
    public String saveMenu(@Valid Menu menu, BindingResult result, Model model) {

        try {
            if (result.hasErrors()) {
                List<ObjectError> errors = result.getAllErrors();
                return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, errors.get(0).getDefaultMessage()).toString();
            }
            menuService.saveMenu(menu);
            menuService.getMenu(menu.getMenuId());
            model.addAttribute("menu",  menuService.getMenu(menu.getMenuId()));
            model.addAttribute("yesOrNoTypeList", CodeInfoCache.getCodeInfo(CodeType.YES_OR_NO));
            return new JsonResponse<Map>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE, FreeMarkerUtil.render("/system/menu/form", model)).toString();
           // return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, SysContant.SAVE_SUCCESS_MESSAGE, menu.getMenuId()).toString();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("数据Menu保存异常！");
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, SysContant.SAVE_ERROR_MESSAGE).toString();
        }
    }
}
